<template>
  <div class="shoplist">
    <ul>
      <li v-for="item in shoplist" :key="item.id">
        <img :src="item.src" alt="">
        <div>
          <p>{{item.title}}</p>
          <p>￥{{item.price}}</p>
          <p><button @click="add(item)">加入购物车</button></p>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
import {mapState} from 'vuex'
// @ is an alias to /src
export default {
	name: 'ShopList',
	// data(){
	// 	return{
	// 		shoplist:[
	// 			{"id":1,'title':'电水壶','price':50.01,'src':"/images/1.jpg"},
	// 			{"id":2,'title':'电压力锅','price':260.99,'src':"/images/2.jpg"},
	// 			{"id":3,'title':'电饭锅','price':200.99,'src':"/images/3.jpg"},
	// 			{"id":4,'title':'电磁炉','price':300.99,'src':"/images/4.jpg"},
	// 			{"id":5,'title':'微波炉','price':400.99,'src':"/images/5.jpg"},
	// 			{"id":6,'title':'电饼铛','price':200.99,'src':"/images/6.jpg"},
	// 			{"id":7,'title':'豆浆机','price':199.99,'src':"/images/7.jpg"},
	// 			{"id":8,'title':'多用途锅','price':510.99,'src':"/images/8.jpg"}
	// 		]
	// 	}
	// }
	
	// 可以通过computed计算属性获取store中的数据
	// computed:{
	// 	shoplist(){
	// 		return this.$store.state.shoplist
	// 	}
	// }
	
	// vuex提供了mapState辅助函数,可以简化computed计算属性的写法
	computed:mapState(['shoplist']),
	methods:{
		add(item){
			// 组件里不能直接变更状态的，可以通过提交一个mutation去变更状态
			// this.$store.commit('add',item);
			
			// 组件里面分发一个action去变更状态
			this.$store.dispatch('add',item);
		}
	}
}
</script>
<style scoped>
	.shoplist{
		width: 100%;
		padding-bottom: 50px;
	}
	li{
		position: relative;
		border-bottom: 1px dashed #CCCCCC;
	}
	li div{
		display: inline-block;
		position: absolute;
		top: 10px;
		width: 120px;
		line-height: 30px;
		font-size: 14px;
	}
	img{
		width: 100px;
		border: 1px solid #ccc;
		margin: 10px 10px 8px 10px;
	}
	li div p:nth-child(2){
		color: #f00;
	}
	button{
		color: white;
		background-color:coral;
		border: 0;
		padding: 0.3125rem;
	}
</style>
